package com.gitee.xmhzzz.component.web;

import cn.hutool.core.collection.CollectionUtil;
import com.gitee.xmhzzz.component.web.intercepter.InterceptorRegisterBean;
import com.gitee.xmhzzz.component.web.intercepter.UserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
  * @ClassName
  * @Description
  * @Author wzq
  * @Date 2023/12/18 10:20
  * @Version 1.0
  */
@Configuration
public class XmhWebMvcConfigurer implements WebMvcConfigurer {

    @Autowired(required = false)
    private List<InterceptorRegisterBean> interceptorRegisterBeans;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //用户拦截器
        UserInterceptor userInterceptor = new UserInterceptor();
        registry.addInterceptor(userInterceptor);
        //实现接口的拦截器
        if(CollectionUtil.isNotEmpty(interceptorRegisterBeans)) {
            for (InterceptorRegisterBean registerBean : interceptorRegisterBeans) {
                registry.addInterceptor(registerBean.interceptor()).addPathPatterns(registerBean.paths()).excludePathPatterns(registerBean.excludePaths());
            }
        }
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        // 兼容现有请求.json的方式
        configurer.favorPathExtension(true)
                .defaultContentType(MediaType.APPLICATION_JSON)
                .mediaType("json", MediaType.APPLICATION_JSON);
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(true);
    }

}
